/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import DTO.Object.Brands.Brands;
import DTO.Object.Catalogue.Catalogues;
import DTO.Products;
import Model.ProductModel;
import Model.SupportUtil;
import Model.marshallXML;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author TuPA
 */
public class Product extends HttpServlet {

    private final String adminPage = "Admin.jsp";

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String realpath = getServletContext().getRealPath("/");
        try {
            boolean isMultipath = ServletFileUpload.isMultipartContent(request);
            if (!isMultipath) {
            } else {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List items = null;
                try {
                    items = upload.parseRequest(request);
                } catch (FileUploadException e) {
                    e.printStackTrace();
                }
                Iterator iter = items.iterator();
                Hashtable params = new Hashtable();
                String filename = null;
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (item.isFormField()) {
                        params.put(item.getFieldName(), item.getString());
                    } else {
                        try {
                            String itemName = item.getName();
                            filename = itemName.substring(itemName.lastIndexOf("\\") + 1);
                            String realPath = getServletContext().getRealPath("/") + "images/product\\" + filename;
                            File saveFile = new File(realPath);
                            item.write(saveFile);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                String button = (String) params.get("btAction");

                if (button.equals("Add")) {
                    String name = (String) params.get("txtProductname");
                    String price = (String) params.get("txtPrice");
                    String descrip = (String) params.get("txtDescrip");
                    String image = "images/product/" + filename;
                    String catalog = (String) params.get("txtCatelog");
                    int proCatalog = 0;
                    Catalogues catalogues = new Catalogues();
                    catalogues = (Catalogues) SupportUtil.unmarshal("DTO.Object.Catalogue", realpath + "XML/Catalogues.xml");
                    for (int i = 0; i < catalogues.getCatalogue().size(); i++) {
                        if (catalogues.getCatalogue().get(i).getCatalogName().equals(catalog)) {
                            proCatalog = i + 1;
                        }
                    }
                    String brand = (String) params.get("txtBrand");
                    int proBrand = 0;
                    Brands brands = new Brands();
                    brands = (Brands) SupportUtil.unmarshal("DTO.Object.Brands", realpath + "XML/Brands.xml");
                    for (int i = 0; i < brands.getBrand().size(); i++) {
                        if (brands.getBrand().get(i).getBrandName().equals(brand)) {
                            proBrand = i + 1;
                        }
                    }
                    String proType = "2";
                    String number = (String) params.get("txtNumber");
                    String from = (String) params.get("txtFrom");
                    String noSell = "0";

                    boolean bInsert = ProductModel.Insert(name, Integer.parseInt(price), descrip, image, proCatalog, Integer.parseInt(proType), Integer.parseInt(number), from, proBrand, Integer.parseInt(noSell));
                    if (bInsert) {
                        marshallXML.marshalProduct(realpath + "XML/products.xml");
                        RequestDispatcher rd = request.getRequestDispatcher(adminPage);
                        rd.forward(request, response);
                    } else {
                        System.out.println("Insert product fail!");
                    }

                } else if (button.equals("Update")) {
                    int positionProduct = 0;
                    String id = (String) params.get("txtID");
                    String name = (String) params.get("txtProductname");
                    String price = (String) params.get("txtPrice");
                    String descrip = (String) params.get("txtDescrip");
                    String catalog = (String) params.get("txtCatelog");
                    String brand = (String) params.get("txtBrand");
                    String image = "images/product/" + filename;
                    String number = (String) params.get("txtNumber");
                    String from = (String) params.get("txtFrom");


                    Products products = (Products) SupportUtil.unmarshal("DTO", realpath + "XML/products.xml");
                    for (int i = 0; i < products.getProduct().size(); i++) {
                        if (products.getProduct().get(i).getProID() == Integer.parseInt(id)) {
                            if (filename != "") {
                                products.getProduct().get(i).setProName(name);
                                products.getProduct().get(i).setPrice(Integer.parseInt(price));
                                products.getProduct().get(i).setDescription(descrip);
                                products.getProduct().get(i).setCatalogName(catalog);
                                products.getProduct().get(i).setBrandName(brand);
                                products.getProduct().get(i).setImage(image);
                                products.getProduct().get(i).setProNumber(Integer.parseInt(number));
                                products.getProduct().get(i).setProFrom(from);
                                positionProduct = i;
                            } else {
                                products.getProduct().get(i).setProName(name);
                                products.getProduct().get(i).setPrice(Integer.parseInt(price));
                                products.getProduct().get(i).setDescription(descrip);
                                products.getProduct().get(i).setCatalogName(catalog);
                                products.getProduct().get(i).setBrandName(brand);
                                products.getProduct().get(i).setProNumber(Integer.parseInt(number));
                                products.getProduct().get(i).setProFrom(from);
                                positionProduct = i;
                            }
                        }
                    }

                    SupportUtil.marshal(realpath + "XML/products.xml", products);

                    ProductModel.updateProductDetail(products, id, positionProduct);

                    RequestDispatcher rd = request.getRequestDispatcher(adminPage);
                    rd.forward(request, response);
                }
            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
